package com.feri.rbacsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feri.rbacsys.bo.CustomLevelAddBo;
import com.feri.rbacsys.bo.LevelConditionAddBo;
import com.feri.rbacsys.bo.LevelPrivilegeAddBo;
import com.feri.rbacsys.common.LevelConditionType;
import com.feri.rbacsys.dao.CustomLevelMapper;
import com.feri.rbacsys.dao.LevelConditionMapper;
import com.feri.rbacsys.dao.LevelPrivilegeMapper;
import com.feri.rbacsys.dto.CustomLevelDto;
import com.feri.rbacsys.entity.CustomLevel;
import com.feri.rbacsys.entity.LevelCondition;
import com.feri.rbacsys.entity.LevelPrivilege;
import com.feri.rbacsys.service.intf.CustomLevelService;
import com.feri.rbacsys.vo.R;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author wmg
* @description 针对表【t_custom_level(客户等级表)】的数据库操作Service实现
* @createDate 2023-03-28 08:52:40
*/
@Service
public class CustomLevelServiceImpl implements CustomLevelService{
    @Resource
    private CustomLevelMapper dao;
    @Resource
    private LevelConditionMapper lcdao;
    @Resource
    private LevelPrivilegeMapper lpdao;
    @Override
    public R addLevel(CustomLevelAddBo bo) {
        if (bo!=null){
            // 遍历等级条件
            for (LevelConditionAddBo lc:bo.getConditions()) {
                LevelCondition levelCondition = new LevelCondition();
                BeanUtils.copyProperties(lc,levelCondition);
                if (levelCondition.getType()==1){
                    levelCondition.setContext("累计消费金额达到"+levelCondition.getMaxValue()+"元");
                }else {
                    levelCondition.setContext("累计购买次数"+levelCondition.getMaxValue()+"笔");
                }
                levelCondition.setLevelName(bo.getName());
                // 判断当前要新增的等级，要新增的升级条件是否已经存在
                LevelCondition level = lcdao.selectOne(new QueryWrapper<LevelCondition>().eq("type", levelCondition.getType()).eq("level_name", levelCondition.getLevelName()));
                if(level==null){
                    lcdao.insert(levelCondition);
                }
            }
            // 遍历等级特权
            for (LevelPrivilegeAddBo lp:bo.getPrivileges()) {
                LevelPrivilege levelPrivilege = new LevelPrivilege();
                BeanUtils.copyProperties(lp,levelPrivilege);
                levelPrivilege.setLevelName(bo.getName());
                lpdao.insert(levelPrivilege);
            }
            // 组装等级对象
            CustomLevel customLevel = new CustomLevel();
            BeanUtils.copyProperties(bo,customLevel);
            // 新增等级
            if (dao.insert(customLevel)>0){
                return R.ok();
            }
        }
        return R.fail("新增等级异常！");
    }

    @Override
    public R query(int page, int size) {
        List<CustomLevelDto> customLevelDtos = dao.queryAllLevel(page, size);
        return R.ok(customLevelDtos);
    }
}




